//
//  NSData+utils.m
//  helper
//
//  Created by huangyi on 12-10-29.
//  Copyright (c) 2012年 huangyi. All rights reserved.
//

#import "NSData+utils.h"
#import "NSString+utils.h"

static NSString* convertDataToHexString(NSData *data){
    const unsigned char *dataBuffer=(const unsigned char *)[data bytes];
    if (!dataBuffer){
        return nil;
    }
    NSUInteger dataLength=[data length];
    NSMutableString *hexString=[NSMutableString stringWithCapacity:(dataLength * 2)];
    for (int i = 0; i < dataLength; ++i){
        [hexString appendString:[NSString stringWithFormat:@"%02x", (unsigned int)dataBuffer[i]]];
    }
    return hexString;
}

@implementation NSData (utils)

-(NSString*)stringValue{
    NSString *string=[[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
    if (!string) {
        string=[[NSString alloc] initWithData:self encoding:NSISOLatin1StringEncoding];
    }
    if (!string) {
        string=[[NSString alloc] initWithData:self encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
    }
    if (!string) {
        string=[[NSString alloc] initWithData:self encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingBig5)];
    }
    if (!string) {
        string=[[NSString alloc] initWithData:self encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingShiftJIS)];
    }
    return string;
}

-(BOOL)isValidJSON{
    BOOL json=YES;
    @try {
        NSError *error=nil;
        [NSJSONSerialization JSONObjectWithData:self options:0 error:&error];
        if (error) {
            json=NO;
        }
    }
    @catch (NSException *exception) {
        json=NO;
    }
    @finally {

    }
    return json;
}

-(id)jsonObject{
    id result=nil;
    NSData *source=self;
    if (![NSJSONSerialization isValidJSONObject:source]) {
        source=self.stringValue.dataValue;
    }
    NSError *error=nil;
    result=[NSJSONSerialization JSONObjectWithData:source options:0 error:&error];
    if (error) {
        NSLog(@"%@",error.description);
    }
    return result;
}
-(id)mutableJsonObject{
    id result=nil;
    NSError *error=nil;
    result=[NSJSONSerialization JSONObjectWithData:self options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        NSLog(@"%@",error.description);
    }
    return result;
}

-(NSString*)hexString{
    return convertDataToHexString(self);
}

-(NSString*)fingerprint{
    int length=64;
    void *sig = NULL;
    sig=malloc(BYTE_SIZE *length);
    [self getBytes:sig length:length];
    NSString *str=[[NSString alloc] initWithBytes:sig length:length encoding:NSASCIIStringEncoding];
    free(sig);
    return str;
}


@end
